<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Str;

/**
 * 订单
 *
 * @Desc:验证请求类
 *
 * @author: zhx
 *
 * @Time: 2023/8/10 10:37
 */
class OrderRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 获取应用于请求的验证规则。
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules()
    {

        return [
            'code_price' => 'required', // 优惠金额
            'price' => 'required', // 总金额
            'code' => '', // 优惠码
            'pid' => 'required',
            'app_id' => 'required',  // 应用ID
            'sid' => 'required',
            'numeral' => 'required', // 购买周期
            'year_unit' => 'required', // 单位1年 2月
            'renew' => 'required',
        ];
    }

    public function messages(): array
    {
        return [
            'code_price.required' => '优惠金额不能为空。',
            'price.required' => '总金额不能为空。',
            'app_id.required' => '应用ID不能为空。',
            'pid.required' => '平台ID不能为空。',
            'sid.required' => '套餐ID不能为空。',
            'numeral.required' => '购买周期不能为空。',
            'year_unit.required' => '周期单位不能为空。',
            'renew.required' => '续费金额不能为空。',
        ];
    }

    public function all($keys = null)
    {
        $data = parent::all($keys);

        // 在这里排除 _token 字段
        unset($data['_token']);
        $data['number'] = md5(Str::uuid());
        $data['type'] = isset($data['type']) ? $data['type'] : 1; //订单类型（1.购买应用）
        $data['is_make'] = 0;
        $data['user_id'] = Request()->user['id'];
        $data['status'] = 0;

        return $data;
    }

    protected function failedValidation(Validator $validator)
    {
        $error = $validator->errors()->all();
        throw new HttpResponseException(response()->json(['msg' => $error[0], 'code' => '500', 'data' => 'error'], 500));
    }
}
